import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, injectIntl } from 'react-intl';
import { stripesConnect,IfPermission } from '@folio/stripes/core';
import get from 'lodash/get';
import { MultiColumnList } from '@folio/stripes/components';
import { StripesConnectedSource } from '@folio/stripes/smart-components';
import ExprotExcel from '../../util/ExportExcel';
import SearchForm from '../../components/party-reader-report/search-form';

class ReaderActStatistics extends Component {
    static manifest = Object.freeze({

      readerReportQuery: { initialValue: '' },
      resultCount: { initialValue: 30 },
      readerDetailsRecords: {
        type: 'okapi',
        path: 'party/reader_attend_data',
        recordsRequired: '%{resultCount}',
        perRequest: 30,
        limitParam: 'limit',
        records: 'readerAttendDataGroup',
        GET: {
          params: {
            query: '${readerReportQuery}'
          }
        }
      },
      activityReaderHttpInvoke: {
        type: 'okapi',
        accumulate: true,
        path: () => 'party/reader_attend_data',

      },

      activityClassificationRequest: {
        type: 'okapi',
        accumulate: true,
        path: () => 'party/property'

      }
    });

    static propTypes = {
      stripes: PropTypes.shape({
        logger: PropTypes.object
      }).isRequired,
      resources: PropTypes.object,
      mutator: PropTypes.shape({

        readerReportQuery: PropTypes.string,
        activityReaderHttpInvoke: PropTypes.shape({
          PUT: PropTypes.func.isRequired,
          POST: PropTypes.func.isRequired,
          GET: PropTypes.func.isRequired,
          DELETE: PropTypes.func.isRequired
        }),
        activityClassificationRequest: PropTypes.shape({
          GET: PropTypes.func.isRequired,
        }),
      }).isRequired,
      dictionary: PropTypes.object
    };

    constructor(props) {
      super(props);
      this.logger = props.stripes.logger;
      this.log = this.logger.log.bind(this.logger);
      this.state = {
        searchForm: {},
        searchFlag:true,
        editOpen: false,
        editParams: {},
        ascriptionList:[],
        optionCategoryList:[]
      };
    }

    componentDidMount() {
      this.source = new StripesConnectedSource(this.props, this.logger);
      this.getClassificationList();
    }

    componentDidUpdate() {
      this.source.update(this.props, 'readerDetailsRecords');
    }

    componentWillUnmount() {
      const { mutator, resources } = this.props;

      mutator.readerReportQuery.replace('');
    }

    search = ({ requestPreferences, creds, ...formData }) => {
      const { mutator } = this.props;

      let query = '';
      if (formData.propertyName) {
        query += ` and propertyName = ${propertyName}* `;
      }
      if (formData.barcode) {
        query += ` and readerReserveGroup == *"barcode"*: *"${formData.barcode}"* `;
      }
      if (formData.readerName) {
        query += ` and readerReserveGroup == *"name"*: *"${formData.readerName}"* `;
      }
      if (!!formData.partyEndDate && !formData.partyStartDate) {
        query += ` and partyEndDate >= "${temp} 00:00:00" and partyEndDate <= "${formData.partyEndDate} 23:59:59" `;
      }
      if (!!formData.partyStartDate && !formData.partyEndDate) {
        query += ` and partyStartDate >= "${formData.partyStartDate} 00:00:00" and partyStartDate <= "${formData.partyStartDate} 23:59:59" `;
      }
      if (!!formData.partyStartDate && !!formData.partyEndDate) {
        query += ` and partyStartDate >= "${formData.partyStartDate} 00:00:00" and partyEndDate <= "${formData.partyEndDate} 23:59:59" `;
      }
      if (query) {
        query = `(${query.substr(4, query.length)})`;
      }

      mutator.readerReportQuery.replace(query);
      if (this.source && this.state.searchFlag) {
        this.source.update(this.props, 'readerDetailsRecords');
        this.setState({
          searchForm: formData,
          searchFlag:false
        }, () => {
          // setTimeout
          setTimeout(() => {
            this.setState({
              searchFlag:true
            });
          }, 500);
        });
      }
    };

    moreData = () => {
      if (this.source) {
        this.source.fetchMore(30);
      }
    };

    exportExcel = () => {
      const params = this.state.searchForm;
      const p = params;
      const okapi = this.props.okapi;
      const path = okapi.url + '/party/reader_attend_data/export_excel';
      const requestParams = ExprotExcel.objToParam(p);
      const fileName = '读者考勤统计';
      const type = 'GET';
      ExprotExcel.exprot(
        path,
        requestParams,
        type,
        fileName,
        okapi.token,
        okapi.tenant
      );
    };

    getClassificationList = () => {
      const list = [];
      const val = JSON.stringify({ ascriptionId: '0' });
      const {intl} = this.props
      const params = {
        params: {
          query: '( isDel = 0 and parentId <> 0 )'
        }
      };
      const { GET } = this.props.mutator.activityClassificationRequest;
      GET(params).then(response => {
        const list = response.propertyGroup;

        if (list) {
          const ascriptionList = [
            {
              value: '',
              label: intl.formatMessage({id:"ui-party.loans.columns.party.propertyName"}) ,
              id: ''
            }
          ];

          list.forEach(value => {
            const tmp = {
              value: value.name,
              label: value.name,
              id: value.id
            };

            ascriptionList.push(tmp);
          });
          this.setState({
            ascriptionList,
            optionCategoryList: list

          });
        }
      });
    };

    render() {
      const {
        resources

      } = this.props;
      if (this.source) {
        this.source.update(this.props, 'readerDetailsRecords');
      }

      const able = document.getElementsByClassName('mclScrollable---IM56u');
      if (able && able[0]) {
        able[0].style.width = '102%';
      }

      const totalCount = this.source ? this.source.totalCount() : 0;
      const dataList = get(resources, 'readerDetailsRecords.records', []);
      const formatter = {
        serialNumber: (
          <FormattedMessage id="ui-party.loans.columns.serialNumber" />
        ),
        reader_number: (
          <FormattedMessage id="ui-party.loans.columns.readerAccount" />
        ),
        reader_name: (
          <FormattedMessage id="ui-party.loans.columns.readerName" />
        ),
        registrations_number: (
          <FormattedMessage id="ui-party.loans.columns.party.reserve.report.reserveAmount" />
        ),

        check_in_number: (
          <FormattedMessage id="ui-party.loans.columns.party.reserve.report.attendAmount" />
        ),
        leave: (
          <FormattedMessage id="ui-party.loans.columns.party.reserve.report.leaveAmount" />
        ),
        check_in_rate: (
          <FormattedMessage id="ui-party.loans.columns.party.reserve.report.addendRate" />
        ),

        leave_rate: (
          <FormattedMessage id="ui-party.loans.columns.party.reserve.report.leaveRate" />
        ),
        absenteeism_rate: (
          <FormattedMessage id="ui-party.loans.columns.party.reserve.report.unAddendRate" />
        )
      };
      return (
        <div>
          <SearchForm
            onSubmit={this.search}
            exportExcel={() => {
              this.exportExcel();
            }}
            ascriptionList={this.state.ascriptionList}
          />
          <MultiColumnList
            interactive={false}
            height={500}
            isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
            totalCount={totalCount}
            virtualize
            contentData={dataList}
            onNeedMoreData={this.moreData}
            columnMapping={formatter}
            columnWidths={{
              serialNumber: '5%',
              reader_number: '20%',
              reader_name: '10%',
              registrations_number: '10%',
              leave: '10%',
              check_in_number: '10%',
              check_in_rate: '10%',
              leave_rate: '10%',
              absenteeism_rate: '10%'
            }}
            visibleColumns={[
              'serialNumber',
              'reader_number',
              'reader_name',
              'registrations_number',
              'check_in_number',
              'leave',
              'check_in_rate',
              'leave_rate',
              'absenteeism_rate'
            ]}
            formatter={{
              serialNumber: item => [<span>{item.rowIndex + 1}</span>],
              reader_number: item => [<span>{item.readeraccount }</span>],
              reader_name: item => [<span>{item.readername }</span>],
              registrations_number: item => [<span>{item.reserveamount }</span>],
              check_in_number: item => [<span>{item.attendamount }</span>],
              leave: item => [<span>{item.leave }</span>],
              check_in_rate: item => [<span>{item.attendrate }</span>],
              leave_rate: item => [<span>{item.leaverate }</span>],
              absenteeism_rate: item => [<span>{item.absenteeismrate }</span>],
            }}
          />
        </div>
      );
    }
}

export default stripesConnect(ReaderActStatistics);
